<template>
  <div class="login-container">
    <div class="login-box">
      <h1>fushen</h1>
      <h2>登录</h2>
      <form @submit.prevent="handleLogin">
        <div class="form-group">
          <label for="username">用户名</label>
          <input 
            id="username" 
            v-model="username" 
            type="text" 
            placeholder="请输入用户名" 
            required
          />
        </div>
        <div class="form-group">
          <label for="password">密码</label>
          <input 
            id="password" 
            v-model="password" 
            type="password" 
            placeholder="请输入密码" 
            required
          />
        </div>
        <button type="submit" class="login-button">登录</button>
      </form>
      <p class="register-text">
        还没有账户？<a href="#" @click="handleRegister">立即注册</a>
      </p>
      <p v-if="error" class="error">{{ error }}</p>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref } from 'vue'
import { useRouter } from 'vue-router'

const username = ref('')
const password = ref('')
const error = ref('')
const router = useRouter()

const handleLogin = async () => {
  try {
    const response = await fetch('http://localhost:3000/api/login', {  // 改为3000端口
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({
        username: username.value,
        password: password.value
      })
    })
    
    const data = await response.json()
    
    if (response.ok) {
      // 保存用户信息到localStorage
      localStorage.setItem('user', JSON.stringify(data.user))
      
      // 跳转到首页
      router.push('/')
    } else {
      error.value = data.error || '登录失败'
    }
  } catch (err) {
    error.value = '网络错误，请稍后重试'
    console.error('Login error:', err)
  }
}

const handleRegister = async () => {
  try {
    const response = await fetch('http://localhost:3000/api/register', {  // 改为3000端口
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({
        username: username.value,
        password: password.value
      })
    })
    
    const data = await response.json()
    
    if (response.ok) {
      // 保存用户信息到localStorage
      localStorage.setItem('user', JSON.stringify(data.user))
      
      // 跳转到首页
      router.push('/')
    } else {
      error.value = data.error || '注册失败'
    }
  } catch (err) {
    error.value = '网络错误，请稍后重试'
    console.error('Registration error:', err)
  }
}
</script>

<style scoped>
/* ... existing styles ... */

.error {
  color: #dc3545;
  margin-top: 1rem;
  text-align: center;
}
</style>